<!DOCTYPE html>
<html lang="zh-CN">
<head><!-- hexo injector head_begin start -->
        <link rel="preconnect" href="undefined" crossorigin="">
        <link rel="preconnect" href="https://cdn.staticfile.org" crossorigin="">
        <link rel="preconnect" href="https://cravatar.cn" crossorigin=""><!-- hexo injector head_begin end -->
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#e7ddc8" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#181c27" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/resources/favicon/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/resources/favicon/favicon-32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/resources/favicon/favicon.ico">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.1.2/css/all.min.css" integrity="sha256-xejo6yLi6vGtAjcMIsY8BHdKsLg7QynVlFMzdQgUuy8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"hyh1370039199.gitee.io","root":"/","images":"/resources/img/","scheme":"Gemini","darkmode":true,"version":"8.12.3","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"flat"},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":true,"comments":{"style":"tabs","active":"utterances","storage":true,"lazyload":false,"nav":null,"activeClass":"utterances"},"stickytabs":true,"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.json","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/config.min.js"></script>

    <meta name="description" content="一些常用数据结构基础太差，来这补习~~😢">
<meta property="og:type" content="article">
<meta property="og:title" content="链表学习笔记----单链表">
<meta property="og:url" content="https://hyh1370039199.gitee.io/post/3/index.html">
<meta property="og:site_name" content="Blog">
<meta property="og:description" content="一些常用数据结构基础太差，来这补习~~😢">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051436235.png">
<meta property="og:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051439971.png">
<meta property="og:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051439936.png">
<meta property="og:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051440808.png">
<meta property="og:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208081705065.png">
<meta property="og:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208081707953.png">
<meta property="article:published_time" content="2022-07-30T10:00:00.000Z">
<meta property="article:modified_time" content="2022-08-18T13:56:02.785Z">
<meta property="article:author" content="hyh">
<meta property="article:tag" content="LeetCode">
<meta property="article:tag" content="链表">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051436235.png">


<link rel="canonical" href="https://hyh1370039199.gitee.io/post/3/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://hyh1370039199.gitee.io/post/3/","path":"/post/3/","title":"链表学习笔记----单链表"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>链表学习笔记----单链表 | Blog</title>
  





<script async defer data-website-id="" src=""></script>



  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-life"><a href="/life/" rel="section"><i class="fas fa-pizza-slice fa-fw"></i>生活</a></li><li class="menu-item menu-item-tech"><a href="/tech/" rel="section"><i class="fas fa-book fa-fw"></i>技术</a></li><li class="menu-item menu-item-reading"><a href="/reading/" rel="section"><i class="fas fa-book fa-fw"></i>阅读</a></li><li class="menu-item menu-item-photos"><a href="/photos/" rel="section"><i class="fas fa-camera-retro fa-fw"></i>相册</a></li><li class="menu-item menu-item-guestbook"><a href="/guestbook/" rel="section"><i class="fas fa-splotch fa-fw"></i>留言</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          目 录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%8D%95%E9%93%BE%E8%A1%A8"><span class="nav-text">一、单链表</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%8A%82%E7%82%B9%E7%BB%93%E6%9E%84"><span class="nav-text">节点结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%93%8D%E4%BD%9C"><span class="nav-text">操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%AE%BE%E8%AE%A1%E9%93%BE%E8%A1%A8"><span class="nav-text">设计链表</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hyh"
      src="/resources/img/avatar.jpg">
  <p class="site-author-name" itemprop="name">hyh</p>
  <div class="site-description" itemprop="description">人生如逆旅，我亦是行人</div>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://gitee.com/hyh1370039199" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;hyh1370039199" rel="noopener" target="_blank"><i class="fa-brands fa-solid fa-g fa-fw"></i></a>
      </span>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hyh1370039199.gitee.io/post/3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/resources/img/avatar.jpg">
      <meta itemprop="name" content="hyh">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Blog">
      <meta itemprop="description" content="人生如逆旅，我亦是行人">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="链表学习笔记----单链表 | Blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          链表学习笔记----单链表
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-07-30 18:00:00" itemprop="dateCreated datePublished" datetime="2022-07-30T18:00:00+08:00">2022-07-30</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/tech/" itemprop="url" rel="index"><span itemprop="name">技术</span></a>
        </span>
    </span>

  
    <span id="/post/3/" class="post-meta-item leancloud_visitors" data-flag-title="链表学习笔记----单链表" title="阅读次数">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span class="leancloud-visitors-count"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="一、单链表">一、单链表</h3>
<p>单链表中的每个节点不仅包含<strong>值</strong>，还包含链接到下一个节点的<strong>引用字段</strong>。通过这种方式，单链表将所有节点按顺序组织起来。</p>
<img data-src="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051436235.png" alt="image-20220805143649613" style="zoom: 25%;" />
<h4 id="节点结构">节点结构</h4>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token comment">// Definition for singly-linked list.</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> <span class="token class-name">List</span>
<span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> data<span class="token punctuation">;</span>
    <span class="token keyword">struct</span> <span class="token class-name">List</span> <span class="token operator">*</span>next<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>List<span class="token punctuation">,</span><span class="token operator">*</span>pList<span class="token punctuation">;</span></code></pre>
<h4 id="操作">操作</h4>
<ol>
<li>
<p><strong>访问操作</strong></p>
<p>与数组不同，我们无法在常量时间内访问单链表中的随机元素。如果我们想要获得第$i$个元素，我们必须从头节点逐个遍历。我们按<strong>索引</strong>来访问元素平均要花费$O(N)$时间，其中N为链表长度。</p>
</li>
<li>
<p><strong>添加操作</strong></p>
<p>如果我们想在<strong>给定</strong>的节点$prev$之后添加新值：</p>
<p>① 使用给定值初始化新节点$cur$。</p>
<img data-src="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051439971.png" alt="image-20220805143816062" style="zoom: 25%;" />
<p>② 将$cur$的$next$字段链接到$prev$的下一个节点$next$。</p>
<img data-src="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051439936.png" alt="image-20220805143917288" style="zoom: 25%;" />
<p>③ 将$prev$中的$next$字段链接到$cur$。</p>
<img data-src="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208051440808.png" alt="image-20220805144017321" style="zoom: 25%;" />
<p>$与数组不同$，我们不需要将所有元素移动到插入元素之后。因此可以在$O(1)$时间复杂度中将新节点插入到链表中。</p>
</li>
<li>
<p><strong>删除操作</strong></p>
<p>从单链表中删除现有节点$cur$：</p>
<p>①找到$cur$的上一个节点$prev$及其下一个节点$next$。</p>
<img data-src="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208081705065.png" alt="image-20220808170543320" style="zoom:25%;" />
<p>②接下来链接$prev$到$cur$的下一个节点$next$。</p>
<img data-src="https://hyh1370039199.oss-cn-chengdu.aliyuncs.com/img/202208081707953.png" alt="image-20220808170734707" style="zoom:25%;" />
<p>第一步中，需要找出$prev$和$next$。使用$cur$的引用字段很容易找出$next$，但是我们必须从头节点遍历链表，以找出$prev$，它的平均时间是$O(N)$,其中N是链表的长度。因此，删除节点的时间复杂度是$O(N)$。空间复杂度为$O(1)$，只需常量空间来存储指针。</p>
</li>
</ol>
<h4 id="设计链表">设计链表</h4>
<p>单链表中的节点应该具有两个属性：$val$ 和 $next$。$val$ 是当前节点的值，$next$ 是指向下一个节点的指针/引用。如果要使用双向链表，则还需要一个属性 $prev$ 以指示链表中的上一个节点。假设链表中的所有节点都是 $0-index$ 的。</p>
<p>在链表类中实现这些功能：</p>
<p>$get(index)$：获取链表中第 $index$ 个节点的值。如果索引无效，则返回$-1$。<br>
$addAtHead(val)$：在链表的第一个元素之前添加一个值为 $val$ 的节点。插入后，新节点将成为链表的第一个节点。<br>
$addAtTail(val)$：将值为 $val$ 的节点追加到链表的最后一个元素。<br>
$addAtIndex(index,val)$：在链表中的第 $index$ 个节点之前添加值为 $val$  的节点。如果 $index$ 等于链表的长度，则该节点将附加到链表的末尾。如果 $index$ 大于链表长度，则不会插入节点。如果$index$小于$0$，则在头部插入节点。<br>
$deleteAtIndex(index)$：如果索引 $index$ 有效，则删除链表中的第 $index$ 个节点。</p>
<h5 id="定义链表结构体">定义链表结构体</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token comment">//定义链表结构体</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> <span class="token class-name">MyLinkedList_t</span>
<span class="token punctuation">&#123;</span>
	<span class="token keyword">int</span> val<span class="token punctuation">;</span><span class="token comment">//值</span>
	<span class="token keyword">struct</span> <span class="token class-name">MyLinkedList_t</span> <span class="token operator">*</span>next<span class="token punctuation">;</span><span class="token comment">//指向下一个节点的指针</span>
<span class="token punctuation">&#125;</span>MyLinkedList<span class="token punctuation">;</span></code></pre>
<p><strong>注意：如果在这个struct定义里，直接把next指针定义为<code>MyLinkedList *next</code>就会报错，因为别名<code>MyLinkedList</code>是在结构体定义结束后才可以识别的一个别名；</strong></p>
<h5 id="创建链表">创建链表</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token comment">//创建链表</span>
MyLinkedList<span class="token operator">*</span> <span class="token function">myLinkedListCreate</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    <span class="token comment">//使用虚拟头节点作为访问、管理链表的入口</span>
    MyLinkedList <span class="token operator">*</span>obj <span class="token operator">=</span> <span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span><span class="token punctuation">)</span><span class="token function">malloc</span><span class="token punctuation">(</span><span class="token keyword">sizeof</span><span class="token punctuation">(</span>MyLinkedList<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//对虚拟链表头进行初始化，此时真实的链表为空</span>
    obj<span class="token operator">-></span>val <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    obj<span class="token operator">-></span>next <span class="token operator">=</span> <span class="token constant">NULL</span><span class="token punctuation">;</span>
    <span class="token comment">//返回链表入口</span>
    <span class="token keyword">return</span> obj<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code></pre>
<h5 id="在链表头部增加节点">在链表头部增加节点</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token comment">//在链表头部增加节点</span>
<span class="token keyword">void</span> <span class="token function">myLinkedListAddAtHead</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>obj<span class="token punctuation">,</span><span class="token keyword">int</span> val<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    MyLinkedList <span class="token operator">*</span>node <span class="token operator">=</span> <span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span><span class="token punctuation">)</span><span class="token function">malloc</span><span class="token punctuation">(</span><span class="token keyword">sizeof</span><span class="token punctuation">(</span>MyLinkedList<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    node<span class="token operator">-></span>val <span class="token operator">=</span> val<span class="token punctuation">;</span>
    <span class="token comment">//将新节点插入至虚拟头节点和原来虚拟头节点下一个节点之间的位置，亦考虑了真实链表为空的情况</span>
    node<span class="token operator">-></span>next <span class="token operator">=</span> obj<span class="token operator">-></span>next<span class="token punctuation">;</span>
    obj<span class="token operator">-></span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code></pre>
<h5 id="在链表尾部增加节点">在链表尾部增加节点</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token comment">//在链表尾部增加节点</span>
<span class="token keyword">void</span> <span class="token function">myLinkedListAddAtTail</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>obj<span class="token punctuation">,</span><span class="token keyword">int</span> val<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    MyLinkedList <span class="token operator">*</span>node <span class="token operator">=</span> <span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span><span class="token punctuation">)</span><span class="token function">malloc</span><span class="token punctuation">(</span><span class="token keyword">sizeof</span><span class="token punctuation">(</span>MyLinkedList<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//由于真实链表可能为空，所以标记位置从obj开始</span>
    MyLinkedList <span class="token operator">*</span>nowList <span class="token operator">=</span> obj<span class="token punctuation">;</span>
    node<span class="token operator">-></span>val <span class="token operator">=</span> val<span class="token punctuation">;</span>
    node<span class="token operator">-></span>next <span class="token operator">=</span> <span class="token constant">NULL</span><span class="token punctuation">;</span>
    <span class="token comment">//一直遍历，直到当前节点的下一个节点为空，当前节点即为尾部节点</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>nowList<span class="token operator">-></span>next <span class="token operator">!=</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        nowList <span class="token operator">=</span> nowList<span class="token operator">-></span>next<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//将原来的尾部节点的下一个节点指向新节点</span>
    nowList<span class="token operator">-></span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code></pre>
<h5 id="获取链表中第-index-个节点的值，从0开始">获取链表中第 $index$ 个节点的值，从0开始</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">myLinkedListGet</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>obj<span class="token punctuation">,</span><span class="token keyword">int</span> index<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    MyLinkedList <span class="token operator">*</span>nowList <span class="token operator">=</span> obj<span class="token operator">-></span>next<span class="token punctuation">;</span>
    <span class="token keyword">int</span> cnt <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
	<span class="token comment">//处理异常情况，index小于0，真实链表为空</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>index <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">||</span> nowList <span class="token operator">==</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//进行链表遍历，循环终止条件：cnt位置达到index位置</span>
    <span class="token comment">//break条件:当前位置节点为空，返回-1</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>cnt <span class="token operator">&lt;</span> index<span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>nowList <span class="token operator">==</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
        <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
        nowList <span class="token operator">=</span> nowList<span class="token operator">-></span>next<span class="token punctuation">;</span>
        cnt<span class="token operator">++</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//循环结束后，取到了当前位置为index的节点，需判断该点为不为空</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>nowList <span class="token operator">!=</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> nowList<span class="token operator">-></span>val<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code></pre>
<h5 id="在链表中的第-index-个节点之前添加值为-val-的节点">在链表中的第 $index$ 个节点之前添加值为 $val$  的节点</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token keyword">void</span> <span class="token function">myLinkedListAddAtIndex</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>obj<span class="token punctuation">,</span><span class="token keyword">int</span> index<span class="token punctuation">,</span><span class="token keyword">int</span> val<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    MyLinkedList <span class="token operator">*</span>nowList <span class="token operator">=</span> obj<span class="token punctuation">;</span>
    <span class="token keyword">int</span> cnt <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
	<span class="token comment">//如果为负索引或者0，直接头插</span>
	<span class="token keyword">if</span><span class="token punctuation">(</span>index <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#123;</span>
		<span class="token function">myLinkedListAddAtHead</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span>val<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//遍历链表，break条件：cnt位置到达index位置,此时nowList节点位置到达index-1位置</span>
	<span class="token keyword">while</span><span class="token punctuation">(</span>nowList<span class="token operator">-></span>next <span class="token operator">!=</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
	<span class="token punctuation">&#123;</span>
		<span class="token keyword">if</span><span class="token punctuation">(</span>cnt <span class="token operator">==</span> index<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token keyword">break</span><span class="token punctuation">;</span><span class="token punctuation">&#125;</span>
		nowList <span class="token operator">=</span> nowList<span class="token operator">-></span>next<span class="token punctuation">;</span>
		cnt<span class="token operator">++</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//如果不满足该条件，一定是通过nowList->next == NULL跳出循环的，index无效</span>
	<span class="token keyword">if</span><span class="token punctuation">(</span>cnt <span class="token operator">!=</span> index<span class="token punctuation">)</span>
	<span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//初始化新节点，将新结点的next节点指向index节点，将index-1位置节点的next节点指向新节点</span>
	MyLinkedList <span class="token operator">*</span>node <span class="token operator">=</span> <span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span><span class="token punctuation">)</span><span class="token function">malloc</span><span class="token punctuation">(</span><span class="token keyword">sizeof</span><span class="token punctuation">(</span>MyLinkedList<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	node<span class="token operator">-></span>val <span class="token operator">=</span> val<span class="token punctuation">;</span>
	node<span class="token operator">-></span>next <span class="token operator">=</span> nowList<span class="token operator">-></span>next<span class="token punctuation">;</span>
	nowList<span class="token operator">-></span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code></pre>
<h5 id="删除链表中的第-index-个节点">删除链表中的第 $index$ 个节点</h5>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token keyword">void</span> <span class="token function">myLinkedListDeleteAtIndex</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>obj<span class="token punctuation">,</span><span class="token keyword">int</span> index<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    MyLinkedList <span class="token operator">*</span>nowList <span class="token operator">=</span> obj<span class="token operator">-></span>next<span class="token punctuation">;</span>
    <span class="token keyword">int</span> cnt <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
	<span class="token comment">//处理异常情况 负索引或者真实链表为空，直接退出</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>index <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">||</span> obj<span class="token operator">-></span>next <span class="token operator">==</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//此时真实链表至少有一个节点，所以可以直接删除第一个</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>index <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        obj<span class="token operator">-></span>next <span class="token operator">=</span> obj<span class="token operator">-></span>next<span class="token operator">-></span>next<span class="token punctuation">;</span>
        <span class="token keyword">return</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//遍历链表，循环终止条件：当前节点为最后一个节点；break条件:当前节点为index位置的前一个节点</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>nowList<span class="token operator">-></span>next <span class="token operator">!=</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>cnt <span class="token operator">==</span> index <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token keyword">break</span><span class="token punctuation">;</span><span class="token punctuation">&#125;</span>
        nowList <span class="token operator">=</span> nowList<span class="token operator">-></span>next<span class="token punctuation">;</span>
        cnt<span class="token operator">++</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token comment">//需满足index位置有节点，且当前节点为index-1位置上的节点，才能进行删除操作</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>cnt <span class="token operator">==</span> index <span class="token operator">-</span> <span class="token number">1</span> <span class="token operator">&amp;&amp;</span> nowList<span class="token operator">-></span>next <span class="token operator">!=</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        nowList<span class="token operator">-></span>next <span class="token operator">=</span> nowList<span class="token operator">-></span>next<span class="token operator">-></span>next<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code></pre>
<h5 id="实现free接口，释放已经申请的内存">实现free接口，释放已经申请的内存</h5>
<p>一个链表，每一个节点都需要释放。但是如果我们直接从第一个节点释放，那么后面的next就无法取到了，链断掉以后，剩下的内存就再也无法访问。所以链表释放内存必须从最后一个开始释放，在释放倒数第二个…依次释放。但是我们遍历链表，从最后一个节点释放，但是链表是单向的，我们无法通过链表取到它上一个节点。所以需要<strong>递归</strong>。</p>
<p>每次只要检查到当前节点还有下一个节点，就先去释放下一个节点，直至找到最后一个节点，然后逐层往回走，最后释放整个链表。</p>
<pre class="language-c" data-language="c"><code class="language-c"><span class="token comment">//递归函数</span>
<span class="token keyword">void</span> <span class="token function">myNodeFree</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>node<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>node<span class="token operator">-></span>next <span class="token operator">!=</span> <span class="token constant">NULL</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token function">myNodeFree</span><span class="token punctuation">(</span>node<span class="token operator">-></span>next<span class="token punctuation">)</span><span class="token punctuation">;</span>
        node<span class="token operator">-></span>next <span class="token operator">=</span> <span class="token constant">NULL</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
    <span class="token function">free</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">void</span> <span class="token function">myLinkedListFree</span><span class="token punctuation">(</span>MyLinkedList <span class="token operator">*</span>obj<span class="token punctuation">)</span>
<span class="token punctuation">&#123;</span>
    <span class="token function">myNodeFree</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code></pre>

    </div>

    
    
    

    <footer class="post-footer">








<div class="license">
  <div class="license-title">链表学习笔记----单链表</div>
  <div class="license-link">
    <a href="https://hyh1370039199.gitee.io/post/3/">https://hyh1370039199.gitee.io/post/3/</a>
  </div>
  <div class="license-meta">
    <div class="license-meta-item">
      <div class="license-meta-title">本文作者</div>
      <div class="license-meta-text">
          hyh
      </div>
    </div>
      <div class="license-meta-item">
        <div class="license-meta-title">发布于</div>
        <div class="license-meta-text">
          2022-07-30
        </div>
      </div>
      <div class="license-meta-item">
        <div class="license-meta-title">更新于</div>
        <div class="license-meta-text">
          2022-08-18
        </div>
      </div>
    <div class="license-meta-item">
      <div class="license-meta-title">许可协议</div>
      <div class="license-meta-text">
          <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank">CC BY-NC-SA 4.0</a>
        
      </div>
    </div>
  </div>
  <div class="license-statement">
      转载或引用本文时，请遵守上述许可协议，注明出处、不得用于商业用途！
    
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/LeetCode/" rel="tag"><i class="fa fa-tag"></i> LeetCode</a>
              <a href="/tags/%E9%93%BE%E8%A1%A8/" rel="tag"><i class="fa fa-tag"></i> 链表</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/2/" rel="prev" title="Hexo-Fluid主题美化-添加网站运行时长">
                  <i class="fa fa-chevron-left"></i> Hexo-Fluid主题美化-添加网站运行时长
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/1/" rel="next" title="CC1101研发笔记">
                  CC1101研发笔记 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner" style="width:100%">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fas fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hyh</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div><!--添加运行时间-->
<span id="sitetime"></span>
<script language=javascript>
	function siteTime(){
		window.setTimeout("siteTime()", 1000);
		var seconds = 1000;
		var minutes = seconds * 60;
		var hours = minutes * 60;
		var days = hours * 24;
		var years = days * 365;
		var today = new Date();
		var todayYear = today.getFullYear();
		var todayMonth = today.getMonth()+1;
		var todayDate = today.getDate();
		var todayHour = today.getHours();
		var todayMinute = today.getMinutes();
		var todaySecond = today.getSeconds();
		/* 
      Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
      year - 作为date对象的年份，为4位年份值
      month - 0-11之间的整数，做为date对象的月份
      day - 1-31之间的整数，做为date对象的天数
      hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
      minutes - 0-59之间的整数，做为date对象的分钟数
      seconds - 0-59之间的整数，做为date对象的秒数
      microseconds - 0-999之间的整数，做为date对象的毫秒数
     */
		var t1 = Date.UTC(2022,06,01,00,00,00); //北京时间2018-2-13 00:00:00
		var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
		var diff = t2-t1;
		var diffYears = Math.floor(diff/years);
		var diffDays = Math.floor((diff/days)-diffYears*365);
		var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
		var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
		var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
		document.getElementById("sitetime").innerHTML=" 本站已安全运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
	}
	siteTime();
</script>
<!--// 添加运行时间-->
<div class="powered">  
    该主题由<a href="https://dlzhang.com" rel="noopener" target="_blank">班班</a>使用 <a href="https://theme-next.js.org" rel="noopener" target="_blank">NexT</a> 主题设计
    <br>
    <a href="/tags/">文章标签</a> · <a href="/policy/">网站政策</a>
</div>

    </div>
  </footer>

  
  <script src="https://cdn.staticfile.org/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdn.staticfile.org/next-theme-pjax/0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
  <script src="https://cdn.staticfile.org/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
  <script src="https://cdn.staticfile.org/pangu/4.0.7/pangu.min.js" integrity="sha256-j+yj56cdEY2CwkVtGyz18fNybFGpMGJ8JxG3GSyO2+I=" crossorigin="anonymous"></script>
<script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/comments.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/utils.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/next-boot.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/pjax.min.js"></script>

  
<script src="https://cdn.staticfile.org/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/third-party/search/local-search.min.js"></script>



  <script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/third-party/fancybox.min.js"></script>


  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


  <script class="next-config" data-name="leancloud_visitors" type="application/json">{"enable":true,"app_id":"xireCeJtnAsdSwG2TIsirxon-MdYXbMMI","app_key":"3NPe30DldW7AfuxsvvdzPo7E","server_url":"https://hyh1370039199.gitee.io/","security":false}</script>
  <script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/third-party/statistics/lean-analytics.min.js"></script>


  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"ams","js":{"url":"https://cdn.staticfile.org/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/third-party/math/mathjax.min.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"1370039199/blog-utterances","issue_term":"pathname","theme":"github-dark"}</script>
<script src="https://cdn.staticfile.org/hexo-theme-next/8.12.3/third-party/comments/utterances.min.js"></script>



<script data-pjax type="text/javascript">
  //jquery selector
  var $linkList = $(".link-list");
  if ($linkList.length != 0) {
    var j = -1;
    for	(var i = 0; i < $linkList.length; i++) {
      const listPath = $linkList[i].getAttribute('json-src');
      const iconPath = $linkList[i].getAttribute('icon-src');
      //使用 getJSON 读取 JSON 文件中的数据
      $.getJSON(listPath, function(data) {
        j++;
        //存储数据的变量 
        var li = "";
        //清空内容 
        $linkList.eq(j).empty();
        //将获取到的 json 格式数据遍历到 div 中
        $.each(data, function(infoIndex, info) {
          var labelWarn = '';
          var labelInfo = '';
          if (info['warn']) { 
            labelWarn = '<span class="label warn">' + info['warn'] + '</span>';
          }
          if (info['info']) { 
            labelInfo = '<span class="label info">' + info['info'] + '</span>';
          }
          li += '<div class="link-list-container">';
          li += '<img class="link-list-image" src="' + iconPath + info['logo'] + '">';
          li += '<p>' + info['title'] + labelInfo + labelWarn + '</p>';
          li += '<p>' + info['intro'] + '</p>';
          li += '<a href="' + info['url'] + '" rel="noopener" target="_blank" data-pjax-state=""></a>';
          li += '</div>';
        })
        //显示处理后的数据 
        $linkList.eq(j).html(li);
      })
    }
  }
</script>



<script data-pjax type="text/javascript">
  //jquery selector
  var $cultureList = $(".culture-list");
  if ($cultureList.length != 0) {
    var j = -1;
    for	(var i = 0; i < $cultureList.length; i++) {
      const listPath = $cultureList[i].getAttribute('json-src');
      const coverPath = $cultureList[i].getAttribute('cover-src');
      //使用 getJSON 读取 JSON 文件中的数据
      $.getJSON(listPath, function(data) {
        j++;
        //存储数据的变量 
        var li = "";
        //清空内容 
        $cultureList.eq(j).empty();
        //将获取到的 json 格式数据遍历到 div 中
        $.each(data, function(infoIndex, info) {
          //影评书评链接
          var title = info['title'];
          if (info['pid']) {
            title = '<a href="/post/'+ info['pid'] +'/" >' + info['title'] +'</a>';
          }

          //作者
          if (info['author']) {
            var author = '<span class="author">' + info['author'] +'</span>';
          } else {
            var author = '';
          }

          //简介
          if (info['intro']) {
            var intro = info['intro'];
          } else {
            var intro = '';
          }
          
          //分数
          if (info['score'] == null) {
            var star = '';
          } else {
            //初始化
            var colorStar = '';
            var greyStar = '';
            var int = info['score'] - info['score'] % 1; //整数部分
            //是否有小数
            var fract = 0; 
            if (info['score'] % 1 != 0) {
              fract = 1;
            }
            //整数星级
            for	(var m = 0; m < int; m++) {
              colorStar += '★';
            }
            //半星级
            if (fract != 0) {
              colorStar += '☆';
            }
            //用空缺星补齐五星
            for	(var m = 0; m < (5 - fract - int); m++) {
              greyStar += '☆';
            }
            if (info['score'] != 5) {
              star = '<span class="star-score">'+ colorStar +'<span class="grey-star">'+ greyStar +'</span></span>';
            } else {
              star = '<span class="star-score">'+ colorStar +'</span>';
            }
          }

          li += '<div class="media">';
          li += '<div class="media-cover" style="background-image:url(' + coverPath + info['cover'] + ')"></div>';
          li += '<div class="media-meta">';
          li += '<div class="media-meta-item title">' + title + '</div>';
          li += '<div class="media-meta-item">' + author + star +'</div>';
          li += '<div class="media-meta-item intro">' + intro + '</div>';
          li += '</div></div>';
        })
        
        //显示处理后的数据 
        $cultureList.eq(j).html(li);
      })
    }
  }
</script>




<script src="/resources/minigrid.min.js"></script>
<script data-pjax type="text/javascript">
  var $album = $(".album")[0];
  if($album) {
    // 相册列表 JSON 数据
    var imgDataPath = $album.getAttribute('json-src');
    // 照片存储路径
    var imgPath = $album.getAttribute('photo-src');
    // 最多显示数量
    var imgMaxNum = 50;
    // 获取窗口大小以决定图片宽度
    var windowWidth = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;
    if (windowWidth < 768) {
        var imageWidth = 145; // 移动端图片宽度
    } else {
        var imageWidth = 235;
    }

    // 腾讯云自定义样式 (数据万象外网流量需要付费)
    //var imgStyle = '!' + imageWidth + 'x';
    //var imgStyle = '!300x';

    // 生成相册
    var LinkDataPath = imgDataPath;
    photo = {
        page: 1,
        offset: imgMaxNum,
        init: function () {
            var that = this;
            $.getJSON(LinkDataPath, function (data) {
                that.render(that.page, data);
            });
        },
        render: function (page, data) {
            var begin = (page - 1) * this.offset;
            var end = page * this.offset;
            if (begin >= data.length) return;
            var imgNameWithPattern, imgName, imageSize, imageX, imageY, li = "";
            for (var i = begin; i < end && i < data.length; i++) {
                imgNameWithPattern = data[i].split(' ')[1];
                imgName = imgNameWithPattern.split('.')[0]
                imageSize = data[i].split(' ')[0];
                imageX = imageSize.split('.')[0];
                imageY = imageSize.split('.')[1];
                li += '<div class="card" style="width:' + imageWidth + 'px" >'
                li += '<div class="album-photo" style="height:'+ imageWidth * imageY / imageX + 'px">'
                li += '<a class="fancybox fancybox.image" href="' + imgPath + imgNameWithPattern + '" itemscope="" itemtype="http://schema.org/ImageObject" itemprop="url" data-fancybox="group" rel="group" data-caption="' + imgName + '" title="' +  imgName + '">'
                li += '<img data-src="' + imgPath + imgNameWithPattern + '" src="' + imgPath + imgNameWithPattern + '" alt="' +  imgName + '" data-loaded="true">'
                li += '</a>'
                li += '</div>'
                li += '</div>'
            }
            $(".album").append(li);
            this.minigrid();
        },

        minigrid: function() {
          var grid = new Minigrid({
              container: '.album',
              item: '.card',
              gutter: 12
          });
          grid.mount();
          $(window).resize(function() {
              grid.mount();
          });
        }
    }
    photo.init();
  }
</script>
</body>
</html>
